package com.huilian.tool.douyin.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.huilian.tool.douyin.web.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author 少凡
 * @Date 2022-12-14 16:17
 * version 1.0
 */
@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 统一返回格式
     *
     * @param result
     * @return
     */
    @Override
    public JSONObject unifiedReturn(String result) {
        JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data");
        String error_code = jsonObject.getString("error_code");

        if ("0".endsWith(error_code)) {
            return jsonObject;
        }
        log.error(result);
        return jsonObject;
    }


    @Override
    public JSONObject getRequest(String url, String accessToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("access-token", accessToken);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        return this.unifiedReturn(response.getBody());
    }

    @Override
    public JSONObject PostRequest(String url, String accessToken, Map<String, Object> params) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("access-token", accessToken);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);

        String result = restTemplate.postForObject(url, entity, String.class);
        return this.unifiedReturn(result);
    }


}
